package com.dao;

import java.util.ArrayList;
import java.util.List;

import com.util.StringUitl;
import org.hibernate.Query;

import com.bean.ResultBean;
import com.bean.TableBean;
import com.bean.TableParamBean;

/**
 * @author Ltz
 */
public class CommonQueryDao {
	/**
	 * 获得数据源
	 * 
	 * @return
	 */
	public List<ResultBean> queryData() {
        String tableName=StringUitl.GetConfigFileParam("tableName");
        String dbName=StringUitl.GetConfigFileParam("dbName");
        if(tableName.equals("")&&dbName.equals("")){
            return null;
        }
        String sqlString ="SELECT TABLE_NAME as tabelName, TABLE_COMMENT as tableComment FROM INFORMATION_SCHEMA.TABLES " +
                "WHERE 1=1 AND TABLE_SCHEMA='"+dbName+"' AND  TABLE_NAME ='"+tableName+"'";
		Query query = HibernateSessionFactory.getSession().createSQLQuery(sqlString);
		List<?> query_list = query.list();
		List<TableBean> tableBeanList = new ArrayList<TableBean>();
		for (int i = 0; i < query_list.size(); i++) {
			TableBean tableBean = new TableBean();
			Object[] object = (Object[]) query_list.get(i);
			tableBean.setTableName(object[0].toString());
			tableBean.setTableComment(object[1].toString());
			tableBeanList.add(tableBean);
		}

		List<ResultBean> rs_list = new ArrayList<ResultBean>();
		for (int a = 0; a < tableBeanList.size(); a++) {
			ResultBean resultBean = new ResultBean();
			List<TableParamBean> tableParamBeanList = new ArrayList<TableParamBean>();
			tableParamBeanList = QueryParamDao(tableBeanList.get(a).getTableName());
			resultBean.setTableParamBean(tableParamBeanList);
			resultBean.setTableBean(tableBeanList.get(a));
			rs_list.add(resultBean);
		}
		return rs_list;
	}

	/**
	 * 查询表结构
	 * 
	 * @param tableName
	 * @return
	 */
	public List<TableParamBean> QueryParamDao(String tableName) {
		Query query = HibernateSessionFactory.getSession().createSQLQuery("select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT from information_schema.columns where table_name=?");
		query.setString(0, tableName);
		List<?> query_list = query.list();
		List<TableParamBean> tableParamBeanList = new ArrayList<TableParamBean>();
		for (int i = 0; i < query_list.size(); i++) {
			TableParamBean tableParamBean = new TableParamBean();
			Object[] object = (Object[]) query_list.get(i);
			tableParamBean.setParamName(object[0].toString());
			tableParamBean.setParamType(object[1].toString());
			tableParamBean.setParamComment(object[2].toString());
			tableParamBeanList.add(tableParamBean);
		}
		return tableParamBeanList;
	}
}
